package org.devops
// 封装HTTP请求
def httpReq(method,reqUrl,reqBody) {
    def sonarApiUrl = "https://sonar.devops.com/api"

    // 增加 Authorization: Basic c3F1XzI3NjAwYjM4OWVmYTlhNTQ5ZjUzOTMzOTQxMGJkOGIxNDRiNDJmZWM6
    // 其中 Basic 后面是密文信息，对应明文是 squ_27600b389efa9a549f539339410bd8b144b42fec:
    // 注意 squ_27600b389efa9a549f539339410bd8b144b42fec 是 sonar 平台为用户生成的 token
    // 注意 结尾的冒号是必须的，表示密码为空，可以使用 base64 编码工具得到密文。
    println("==================================================")
    withCredentials([string(credentialsId: "sonar-token", variable: 'sonarToken')]) {
        result = httpRequest httpMode: method,
                customHeaders: [[maskValue: true, name: 'Authorization', value: 'Bearer ' + sonarToken]],
                url: "${sonarApiUrl}/${reqUrl}",
                contentType: "APPLICATION_JSON_UTF8",
                requestBody: reqBody,
                quiet: true,
                ignoreSslErrors: false,
                acceptType: 'APPLICATION_JSON_UTF8',
                consoleLogResponseBody: true
    }
    println("==================================================")
    return result
}

// 搜索Sonar项目
def searchProject(projectName){
    reqUrl = "projects/search?projects=${projectName}"
    response = httpReq("GET", reqUrl, '')

    response = readJSON text: """${response.content}"""
    result = response["paging"]["total"]
    if (result.toString() == "0") {
        return "false"
    } else {
        return "true"
    }
}

// 创建Sonar项目
def createProject(projectName){
    reqUrl = "projects/create?name=${projectName}&project=${projectName}"
    response = httpReq("POST", reqUrl, '')
    println(response)
}

// 配置项目质量规则
def configQualityProfiles(projectName, lang, qualityProfile) {
    reqUrl = "qualityprofiles/add_project?language=${lang}&project=${projectName}&qualityProfile=${qualityProfile}"
    response = httpReq("POST", reqUrl, '')
    println(response)
}

// 获取质量阈ID
def getQualtyGateId(gateName) {
    reqUrl = "qualitygates/show?name=${gateName}"
    response = httpReq("GET", reqUrl, '')
    response = readJSON text: """${response.content}"""
    result = response["id"]
    return result
}

// 配置项目质量阈
def configQualityGates(projectName, gateName) {
    //gateId = getQualtyGateId(gateName)
    reqUrl = "qualitygates/select?gateName=${gateName}&projectKey=${projectName}"
    response = httpReq("POST", reqUrl, '')
    println(response)
}

// 获取Sonar质量阈状态
def getProjectStatus(projectName){
    reqUrl = "project_branches/list?project=${projectName}"
    response = httpReq("GET", reqUrl, '')
    response = readJSON text: """${response.content}"""
    result = response["branches"][0]["status"]["qualityGateStatus"]
    return result
}

// 获取Sonar质量阈状态(多分支)
def getProjectStatus(projectName, branch){
    reqUrl = "qualitygates/project_status?projectKey=${projectName}&branch=${branch}"
    response = httpReq("GET", reqUrl, '')
    response = readJSON text: """${response.content}"""
    result = response["projectStatus"]["status"]
    return result
}

def sonarScan(projectName, projectDesc, tagName, branch) {
    withSonarQubeEnv("sonar-server") {
        // env.SONAR_HOST_URL 和 env.SONAR_AUTH_TOKEN 来自 jenkins 的 sonarqube scanner 插件配置
        // 并且会自动注入到命令行中，所以命令行不用单独指定这两个变量

        def modNameList = new ArrayList()
        dir('.') {
            def files = findFiles()
            files.each{ file ->
                if (file.directory && file.name.startsWith("${projectName}")) {
                    modNameList.add(file.name)
                }
            }
        }

        strModNames = modNameList.join(",")

        sh """
           sonar-scanner \
           -Dsonar.projectKey=${projectName} \
           -Dsonar.projectName=${projectName} \
           -Dsonar.projectDescription="${projectDesc}" \
           -Dsonar.projectVersion=${tagName} \
           -Dsonar.ws.timeout=30 \
           -Dsonar.modules=${strModNames} \
           -DsourceEncoding=UTF-8 \
           -Dsonar.links.homepage=${env.gitlabAddr} \
           -Dsonar.links.ci=${env.BUILD_URL} \
           -Dsonar.language=java \
           -Dsonar.sources=src/main/java \
           -Dsonar.test=src/test/java \
           -Dsonar.java.binaries=target/classes \
           -Dsonar.java.test.binaries=target/test-classes \
           -Dsonar.java.surefire.report=target/surefire-reports \
           -Dsonar.branch.name=${branch}
       """
    }

    // 等待质量门检测通过
    timeout(time: 15, unit: 'MINUTES')  {
        def result = waitForQualityGate()
        if (result.status != "OK") {
            error "Pipeline aborted due to quality gate failure: ${result.status}"
        }
    }
}
